// pages/songDetail/songDetail.js
import request from '../../../utils/request'
import PubSub from 'pubsub-js'
import moment from 'moment'
// const appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPlay: false,//音乐是否播放
    songInfo: {},//歌曲详情
    songUrl: '',//歌曲播放地址
    currentTime: '00:00',//已播放时长
    durationTime: '00:00',//总时长
    lyricList: [],//歌词列表
    currentLyric: '',//当前歌词
    currentValue:0,//当前播放的百分比
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    /* const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('getSongItem', async (data) => {
      console.log('data')
    }) */
    let musicId = options.ids
    this.getSongInfo(musicId)
    this.getLrc(musicId)
    //系统按钮控制音乐播放的状态要传递给页面
    /* if(appInstance.globalData.isMusicPlay && appInstance.globalData.musicId === musicId){
      this.setData({
        isPlay:true
      })
    } */
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    //监听音乐播放/暂停
    this.backgroundAudioManager.onPlay(() => {
      this.changePlayState(true);
      // appInstance.globalData.musicId = musicId;
    })
    this.backgroundAudioManager.onPause(() => {
      this.changePlayState(false)
    })
    this.backgroundAudioManager.onStop(() => {
      this.changePlayState(false)
    })
    //监听音乐播放进度
    this.backgroundAudioManager.onTimeUpdate(() => {
      //格式化实时播放进度
      let currentTime = moment(this.backgroundAudioManager.currentTime * 1000).format('mm:ss')
      this.setData({
        currentTime
      })
      //设置当前进度条宽度
      let currentValue = (this.backgroundAudioManager.currentTime * 1000) / this.data.songInfo.dt * 100
      this.setData({
        currentValue
      })
      //设置当前歌词
      this.getCurrentLyric(this.backgroundAudioManager.currentTime)
    })

    //监听音乐播放自然结束
    this.backgroundAudioManager.onEnded(() => {
      //自动切换为下一首
      PubSub.publish('getType', 'next')
      //将实时进度条还原为0
      this.setData({
        currentWidth: 0,
        currentTime: '00:00'
      })
    })
  },
  //获取当前歌词并设置
  getCurrentLyric(currentTime) {
    let time =  Math.floor(currentTime)
    let res = this.data.lyricList.find(item => item.time == time)
    if (res) {
      this.setData({
        currentLyric:res.text
      })
    }
  },
  //修改播放状态
  changePlayState(state) {
    this.setData({
      isPlay: state
    })
    //修改全局播放状态
    // appInstance.globalData.isMusicPlay = state
  },
  //获取音乐详情并播放
  async getSongInfo(ids) {
    //获取音乐详情数据
    let songInfoData = await request('/song/detail', { ids })
    //获取音乐播放地址
    let musicLinkData = await request('/song/url', { id: ids })
    //格式化时间
    let durationTime = moment(songInfoData.songs[0].dt).format('mm:ss')
    this.setData({
      songInfo: songInfoData.songs[0],
      songUrl: musicLinkData.data[0].url,
      durationTime,
      isPlay: true
    })
    wx.setNavigationBarTitle({
      title: this.data.songInfo.name,
    })
    this.backgroundAudioManager.src = this.data.songUrl;
    this.backgroundAudioManager.title = this.data.songInfo.name;
  },
  //获取歌词并处理
  async getLrc(musicId) {
    let lrcData = await request('/lyric', { id: musicId })
    let res = this.handleLrc(lrcData.lrc.lyric)
    this.handleLrc(res)
  },
  //处理歌词
  handleLrc(lrcText) {
    let result = []
    if (lrcText) {
      let lrcArr = lrcText.split('\n');
      let len = lrcArr.length - 1;
      for (let i = 0; i < len; i++) {
        let itemObj = {}
        let item = lrcArr[i]
        let rowArr = item.split(']')
        let text = rowArr.pop();
        let timeArr = rowArr[0].substr(1, rowArr[0].length - 1).split(':');
        let time = parseInt(timeArr[0]) * 60 + Math.floor(timeArr[1]);
        itemObj.text = text;
        itemObj.time = time;
        result.push(itemObj)
      }
      this.setData({
        lyricList: result
      })
    }

  },
  //处理播放、暂停的回调
  handleMusicPlay() {
    let isPlay = !this.data.isPlay
    this.musicControl(isPlay)
  },
  //控制音乐播放、暂停的功能函数
  async musicControl(isPlay) {
    if (isPlay) {
      this.backgroundAudioManager.src = this.data.songUrl;
      this.backgroundAudioManager.title = this.data.songInfo.name
    } else {
      this.backgroundAudioManager.pause();
    }
  },
  //切换上一首/下一首的回调
  handleSwitch(event) {
    //获取切歌类型
    let type = event.currentTarget.id;
    //关闭当前背景音乐
    this.backgroundAudioManager.stop();
    PubSub.subscribe('getMusicId', (msg, musicId) => {
      this.getSongInfo(musicId)
      PubSub.unsubscribe('getMusicId')
    })
    PubSub.publish('getType', type)
  },
  //处理进度条拖动的回调
  handleProgress(e){
    this.backgroundAudioManager.seek(e.detail.value  * this.data.songInfo.dt / 100000)
    this.setData({
      currentValue:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})